package com.rr.jvm.demo;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuangcanrun
 * @Date 2021/12/14/0:18
 * @description
 **/

/*
 * 弱引用测试，该部分对象只能活到下一次垃圾回收
 * 虚拟机参数：-Xmx20m -XX:+PrintGCDetails -verbose:gc
 * */
public class Demo3WeakReferenceTest {

    private static final int _4MB = 4 * 1024 * 1024;

    public static void main(String[] args) {
        List<WeakReference<byte[]>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            WeakReference<byte[]> ref = new WeakReference<>(new byte[_4MB]);
            list.add(ref);
            for (WeakReference<byte[]> weakReference : list) {
                System.out.print(weakReference.get());
            }
            //触发full gc时会把新生代老年代的所有弱引用都回收掉，monitor gc只回收新生代的弱引用

            //不手动full gc的话会有个头一直不被回收
//            System.gc();
            System.out.println();
        }
        System.out.println("跳出循环,list.size="+list.size());
    }
}
